import 'package:flutter/material.dart';
import 'package:helloworld/res/depositData.dart';
import 'package:helloworld/res/incomeData.dart';
import 'package:helloworld/tabs.dart';
import 'package:dio/dio.dart';
import 'dart:ui';
import 'package:flutter_cupertino_date_picker/flutter_cupertino_date_picker.dart';
import 'package:date_format/date_format.dart';
import 'package:helloworld/pages/inCome.dart';
class AddIncome extends StatefulWidget{
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _AddIncome();
  }
}
class _AddIncome extends State<AddIncome> with WidgetsBindingObserver{
  var _date = TextEditingController();
  DateTime _dateData;
  var incomeData = TextEditingController();
  var _depositid;
  var _depositcount;
  var _depositnumber;
  var _deposit;
  int _index = 0;
  Color _textColor;
  String payWay = '请选择';
  int flag = 1;
  Brightness brightnessValue;
  Widget _payWayDialog(){
    if(flag==1){
      return SingleChildScrollView(
        child: Column(
          children: depositData.asMap().keys.map((f) {
            return Column(
              children: <Widget>[
                Divider(),
                Container(
                  child: ListTile(
                    title:
                    Text(depositData[f]['depositcount']),
                    subtitle:
                    Text(depositData[f]['depositnumber']),
                    trailing: Text(
                      depositData[f]['deposit'].toString(),
                    ),
                    onTap: () {
                      setState(() {
                        _index = f;
                        payWay = depositData[_index]['depositcount'];
                        Navigator.pop(context);
                      });
                    },
                  ),
                  height: 60,
                ),
              ],
            );
          }).toList(),
        ),
        scrollDirection: Axis.vertical,
      );
    }else{
      return Center(
        child: Text('暂无存款账户',style: TextStyle(color: _textColor,fontSize: 30),),
      );
    }
  }
  @override
  void didChangePlatformBrightness() {
    // TODO: implement didChangePlatformBrightness
    super.didChangePlatformBrightness();
    if (window.platformBrightness == Brightness.dark) {
      _textColor = Colors.white54;
    } else {
      _textColor = Colors.black54;
    }
  }
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    if(depositData.length==0) flag = 0;
    _dateData = DateTime.now();
    _date.text = '${formatDate(_dateData, [mm, '月', dd, '日'])}';
    WidgetsBinding.instance.addObserver(this);
    brightnessValue = window.platformBrightness;
    if (window.platformBrightness == Brightness.dark) {
      _textColor = Colors.white54;
    } else {
      _textColor = Colors.black54;
    }
  }
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
        title: Text('添加收入'),
        actions: <Widget>[
          InkWell(
            child: Padding(
              child: Text(
                '保存',
                style: TextStyle(color: Colors.white, fontSize: 20),
              ),
              padding: EdgeInsets.all(16),
            ),
            onTap: () {
              _depositid = depositData[_index]['depositid'];
              _depositcount = depositData[_index]['depositcount'];
              _depositnumber = depositData[_index]['depositnumber'];
              _deposit = depositData[_index]['deposit']+double.parse(incomeData.text);
              Dio().post("http://123.207.114.127:1314/deposit/updateDeposit",queryParameters: {
                'depositid':_depositid,
                'depositcount':_depositcount,
                'depositnumber':_depositnumber,
                'deposit': _deposit
              });
              Dio().post("http://123.207.114.127:1314/income/addIncome",queryParameters: {
                'incomename': payWay,
                'incomedate':'${formatDate(_dateData, [mm, '月', dd, '日'])}',
                'income': double.parse(incomeData.text),
                'incomeyear': '${formatDate(_dateData, [
                  yyyy,
                ])}',
                'incomemonth':'${formatDate(_dateData, [
                  mm,
                ])}',
                'incomeday':'${formatDate(_dateData, [
                  dd,
                ])}',
              });
              Future.delayed(Duration(milliseconds: 50), () {
                Navigator.of(context).pop();
                Navigator.pushReplacementNamed(context, '/inCome'
                );              });
            },
          )
        ],
      ),
      body: Padding(
        padding: EdgeInsets.all(20),
        child: SingleChildScrollView(
          child: Column(
            children: <Widget>[
              InkWell(
                child: Container(
                  decoration: BoxDecoration(
                      border: Border.all(width: 1, color: Colors.grey),
                      borderRadius: BorderRadius.circular(4)),
                  height: 60,
                  width: double.infinity,
                  child: Row(
                    children: <Widget>[
                      SizedBox(
                        width: 10,
                      ),
                      Expanded(
                        flex: 2,
                        child: Text(
                          '收入账户',
                          style: TextStyle(fontSize: 16, color: _textColor),
                        ),
                      ),
                      Expanded(
                        flex: 1,
                        child: Container(
                          child:Row(
                            mainAxisAlignment: MainAxisAlignment.end,
                            children: <Widget>[
                              Text(
                                payWay,
                                style: TextStyle(fontSize: 16, color: _textColor),
                              ),
                              SizedBox(
                                width: 10,
                              ),
                              Icon(
                                Icons.navigate_next,
                                color: _textColor,
                              )
                            ],
                          ),
                          width: 100,
                          height: 60,
                          // color: Colors.greenAccent,
                        ),
                      )

                    ],
                  ),
                ),
                onTap: () {
                  showDialog(
                      context: context,
                      builder: (context) {
                        return AlertDialog(
                          title: Row(
                            children: <Widget>[
                              Expanded(
                                child: Text("选择收入账户"),
                                flex: 5,
                              ),
                              Expanded(
                                child: IconButton(
                                  icon: Icon(Icons.close),
                                  onPressed: (){
                                    Navigator.pop(context);
                                  },
                                ),
                                flex: 1,
                              )

                            ],
                          ),
                          content: Container(
                            child: _payWayDialog(),
                            height: 240,
                          ),
                        );
                      });
                },
              ),
              SizedBox(height: 10,),
              TextField(
                keyboardAppearance: brightnessValue,
                keyboardType: TextInputType.numberWithOptions(decimal: true),
                decoration: InputDecoration(
                    border: OutlineInputBorder(), labelText: '收入金额'),
                onChanged: (value) {
                  setState(() {
                    incomeData.text = value;
                  });
                },
              ),
              SizedBox(
                height: 10,
              ),
              InkWell(
                child: TextField(
                  controller: _date,
                  enabled: false,
                  decoration: InputDecoration(
                      border: OutlineInputBorder(), labelText: '日期'),
                ),
                onTap: () {
                  DatePicker.showDatePicker(
                    context,
                    onMonthChangeStartWithFirstDate: true,
                    pickerTheme: DateTimePickerTheme(
                      showTitle: true,
                      confirm: Text('确定',
                          style: TextStyle(color: Colors.black54, fontSize: 20)),
                      cancel: Text('取消',
                          style: TextStyle(color: Colors.black54, fontSize: 20)),
                    ),
                    minDateTime: DateTime.parse('2020-01-01'),
                    maxDateTime: DateTime.parse('2099-12-31'),
                    initialDateTime: _dateData,
                    dateFormat: 'MMMM-dd',
                    locale: DateTimePickerLocale.zh_cn,
                    onConfirm: (dateTime, List<int> index) {
                      setState(() {
                        _dateData = dateTime;
                        _date.text =
                        '${formatDate(_dateData, [mm, '月', dd, '日'])}';
                      });
                    },
                  );
                },
              ),

            ],
          ),
          scrollDirection: Axis.vertical,
        ),
      ),
    );
  }
  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    WidgetsBinding.instance.removeObserver(this);
  }
}